package io.jt808.proto.req;

import io.norland.buffer.AutoBuffer;
import io.norland.annotations.Proto;
import io.norland.proto.IProto;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * CAN 总线数据上传
 */
@Proto("0705")
@Data
public class JT0705 implements IProto {
    private short itemNum;

    private String receiveTime;


    private List<CanDataItem> canDataList;


    public final byte[] writeToBytes() {
        AutoBuffer buffer = new AutoBuffer();
        buffer.writeShort(itemNum);
        buffer.writeBcdString(receiveTime, 5);
        for (CanDataItem item : canDataList) {
            buffer.writeInt(item.canId);
            buffer.writeLong(item.canData);
        }
        return buffer.array();
    }

    public final void readFromBuf(AutoBuffer buff) {
        itemNum = buff.readShort();
        receiveTime = buff.readBcdString(5);
        canDataList = new ArrayList<>();
        while (buff.isReadable()) {
            CanDataItem item = new CanDataItem();
            item.canId = buff.readInt();
            item.canData = buff.readLong();
            canDataList.add(item);
        }
    }

    public class CanDataItem {
        /**
         * bit31 表示 CAN 通道号，0：CAN1，1：CAN2；
         * bit30 表示帧类型，0：标准帧，1：扩展帧；
         * bit29 表示数据采集方式，0：原始数据，1：采
         * 集区间的平均值；
         * bit28-bit0 表示 CAN 总线 ID。
         */
        private int canId;
        private long canData;

        public boolean isCAN1() {
            return (canId & 1 << 31) == 0;
        }

        public boolean isClassFrame() {
            return (canId & 1 << 30) == 0;
        }

        public boolean isOriginData() {
            return (canId & 1 << 29) == 0;
        }

        public long getCANId() {
            return canId & 0x1FFFFFFFL;
        }
    }

//    public static void main(String[] args) {
//        byte[] bytes = new byte[]{
//                0x00, 0x01,
//                0x11, 0x03, 0x03, 0x04, 0x01,
//                (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
//                0x00, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF
//        };
//        JT0705 jt0705 = new JT0705();
//        jt0705.readFromBuf(new AutoBuffer(bytes));
//        System.out.println(new String(bytes).equals(new String(jt0705.writeToBytes())));
//        System.out.println(jt0705.canDataList.get(0).getCANId());
//    }
}